<template>
  <div>
    <el-row :gutter="20">
      <!-- 左侧部分 -->
      <el-col :span="12">
        <el-card class="left-card">
          <div slot="header" class="clearfix">
            <span>新网站的主要信息</span>
          </div>
          <el-form ref="form" :model="form" label-width="150px" :rules="rules">
            <!-- 部署的集群 -->
            <el-form-item label="部署的集群" prop="cluster">
              <el-select v-model="form.cluster" placeholder="请选择集群" class="select">
                <el-option
                  v-for="item in clusters"
                  :key="item.clusterId"
                  :label="item.clusterName"
                  :value="item.clusterId"
                ></el-option>
              </el-select>
              <span class="el-form-item__helper">当前网站将会部署到所选集群的节点上。</span>
            </el-form-item>

            <!-- 绑定域名 -->
            <el-form-item label="绑定域名" prop="domains">
              <!-- 显示已绑定的域名和添加域名按钮 -->
              <div v-if="form.domains.length > 0" class="domain-list">
                <el-tag
                  v-for="(domain, index) in form.domains"
                  :key="index"
                  closable
                  @close="removeDomain(index)"
                  class="domain-tag"
                >
                  {{ domain }}
                </el-tag>
              </div>
              <el-button @click="openDomainDialog" type="text">[添加域名]</el-button>
              <span class="el-form-item__helper">绑定后，才能通过域名访问不同的服务。</span>
            </el-form-item>

            <!-- 源站地址 -->
            <el-form-item label="源站地址" prop="origin">
              <el-input v-model="form.origin" placeholder="点击选择或添加源站地址" @click="openOriginDialog">
                <template slot="append">
                  <el-button @click="openOriginDialog">添加源站地址</el-button>
                </template>
              </el-input>
              <span class="el-form-item__helper">可以通过CDN边缘节点分发源站内容。</span>
            </el-form-item>

            <el-form-item label="绑定端口" prop="portParamsList">
              <div class="port-tags">
                <el-tag
                  v-for="(port, index) in form.portParamsList"
                  :key="index"
                  closable
                  @close="removePort(index, port)"
                  class="port-tag"
                >
                  {{ port.protocol === '0' ? 'http' : 'https' }}://*:{{ port.port }}
                </el-tag>
                <el-button type="text" size="small" @click="openPortDialog">修改</el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧部分 -->
      <el-col :span="12">
        <el-card class="right-card">
          <div slot="header" class="clearfix">
            <span>网站的次要信息</span>
          </div>
          <el-form ref="formRight" :model="form" label-width="150px">
            <!-- 网站类型 -->
            <el-form-item label="网站类型">
              <el-select v-model="form.websiteType">
                <el-option
                  v-for="dict in dict.type.edge_website_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
              <span class="el-form-item__helper">可以是网站用途或者域名等。</span>
            </el-form-item>

            <!-- 网站名称 -->
            <el-form-item label="网站名称">
              <el-input v-model="form.websiteName" placeholder="输入网站名称"/>
            </el-form-item>

          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗区域 -->
    <div>

      <!-- 其他弹窗 -->
      <el-dialog :visible.sync="domainDialogVisible" title="添加域名绑定">
        <!-- 显示单个域名输入框 -->
        <div v-if="!isBatchAdd">
          <el-input v-model="form.newDomain" placeholder="请输入新的域名"/>
          <span class="el-form-item__helper">
      请输入单个域名，比如 example.com、www.example.com ，不要包含 http:// 或 https:// 或端口号；也可以使用泛域名，比如 *.example.com。
    </span>
        </div>

        <!-- 显示批量域名输入框 -->
        <div v-if="isBatchAdd">
          <el-input
            type="textarea"
            v-model="form.newDomain"
            placeholder="请输入多个域名，每个域名之间用换行或逗号分隔"
            rows="4"
          ></el-input>
          <span class="el-form-item__helper">
      输入多个域名，使用换行符或逗号分隔。请勿包含 http://、https:// 或端口号。
    </span>
        </div>

        <div slot="footer" class="dialog-footer">
          <!-- 切换单个和批量添加 -->
          <el-button @click="toggleBatchAdd" type="text">
            {{ isBatchAdd ? "切换到单个添加" : "批量添加" }}
          </el-button>
          <el-button @click="domainDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addDomain">确定</el-button>
        </div>
      </el-dialog>

      <el-dialog :visible.sync="originDialogVisible" title="添加源站地址" width="50%">
        <el-form ref="ipForm" :model="originForm" :rules="originFormRules" label-width="150px">

          <el-form-item label="源站协议" prop="protocol">
            <el-select v-model="form.protocol">
              <el-option
                v-for="dict in dict.type.edge_network_protocols"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="源站地址" prop="origin">
            <el-input v-model="form.origin"></el-input>
            <span
              class="help-text">源站服务器地址,通常是一个IP(或域名)加端口,80和443端口可以省略，不需要加http://或https://。</span>
          </el-form-item>


          <el-form-item label="回源主机名" prop="originHost">
            <el-input v-model="form.originHost" placeholder="回源主机名"/>
            <span
              class="help-text">可选项,请求源站时的Host字段值,用于设置访问源站的站点域名,支持请求变量;如果用户访问的域名和源站域名不一致,请务必设置为源站域名。</span>
          </el-form-item>

          <div class="more-options">
            <el-button type="text" @click="toggleRemark">
                <span :class="{ 'bold-font': !showRemark }">
                  {{ showRemark ? '收起选项 ▲' : '更多选项 ▼' }}
                </span>
            </el-button>
          </div>

          <!-- 专属域名和端口跟随显示控制 -->
          <el-form-item v-if="showRemark" placeholder="专属域名">
            <el-button type="text" @click="toggleDomainInput">[添加专属域名]</el-button>
          </el-form-item>

          <!-- 专属域名输入框 -->
          <el-form-item label="专属域名" class="install-option" v-if="showDomainInput">
            <el-input v-model="form.newDomain" placeholder="请输入新的专属域名"/>
            <el-button type="text" @click="addDomainToList">[保存]</el-button>
            <span
              class="help-text">默认不需要填写,表示支持所有域名,如果填写了专属域名,表示这些源站只会在所列的专属域名被访问时才生效。</span>
          </el-form-item>

          <!-- 显示已添加的专属域名 -->
          <el-form-item v-if="form.exclusiveDomains.length > 0">
            <div>
              <strong>已添加专属域名:</strong>
              <ul>
                <li v-for="(domain, index) in form.exclusiveDomains" :key="index">{{ domain }}</li>
              </ul>
            </div>
          </el-form-item>

          <!-- 端口跟随 -->
          <el-form-item label="端口跟随" class="install-option" v-if="showRemark">
            <el-checkbox v-model="form.portFollowing"></el-checkbox>
            <span
              class="help-text">选中后,表示源站的端口保持和用户访问的服务端口保持一致;此时的源站地址的端口号可以任意填写。</span>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="originDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrigin">确定</el-button>
        </span>
      </el-dialog>

      <el-dialog :visible.sync="portDialogVisible" title="修改端口">

        <el-form :model="form" :rules="originFormRules" label-width="150px">

          <el-form-item label="源站协议" prop="protocol">
            <el-select v-model="form.protocol">
              <el-option
                v-for="dict in dict.type.edge_network_protocols"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="端口">
            <el-input v-model="form.newPort" placeholder="请输入端口"/>
            <span
              class="help-text">可以是一个数字端口（通常不超过65535）,也可以是"地址:端口"的方式。HTTP常用的端口为80</span>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="portDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addPort">确定</el-button>
        </span>

      </el-dialog>

      <div>
        <el-button type="primary" @click="Cancel" class="cancel">取消</el-button>
        <el-button type="primary" @click="Submit" class="submit">提交</el-button>
      </div>
    </div>

  </div>
</template>

<script>
import {listClusters} from "@/api/nodes/clusters";
import {addServer} from "@/api/website/server";

export default {
  dicts: ['edge_network_protocols', 'edge_website_type'],
  data() {
    return {
      form: {
        cluster: '',
        newDomain: '',
        domains: [],  // 修改为数组，允许多个域名,
        origin: '',
        websiteType: '0',
        websiteName: '',
        portParamsList: [
          {
            "protocol": "0",
            "port": "80"
          }
        ],
        exclusiveDomains: [],  // 存储专属域名列表
      },
      originForm: {},
      isBatchAdd: false,  // 控制是否显示批量添加域名
      domainDialogVisible: false,
      originDialogVisible: false,
      groupDialogVisible: false,
      portDialogVisible: false,
      certificateDialogVisible: false,
      existingCertificateDialogVisible: false, // 选择已有证书弹窗
      uploadCertificateDialogVisible: false, // 上传证书弹窗
      clusters: [],
      showRemark: false,
      portFollowing: false,
      origin: '',
      originHost: '',
      showDomain: false,
      showDomainInput: false, // 控制专属域名输入框的显示与隐藏

      originFormRules: {
        protocol: [{required: true, message: '源站协议不能为空', trigger: 'blur'}],
        origin: [{required: true, message: '源站地址不能为空', trigger: 'blur'}],
      },
      rules: {
        cluster: [{required: true, message: '部署的集群不能为空', trigger: 'blur'}],
        domain: [{required: true, message: '绑定的域名不能为空', trigger: 'blur'}],
        origin: [{required: true, message: '源站地址不能为空', trigger: 'blur'}],
        ports: [{required: true, message: '绑定的端口不能为空', trigger: 'blur'}],
      },

    };
  },
  created() {
    this.getClusterList();
  },
  methods: {
    resetOriginForm() {
      this.originForm = {
        protocol: null,
        origin: '',
        originHost: '',
        newDomain: '',
        portFollowing: false,
      };
      this.$refs.originForm.resetFields();
    },

    // 切换显示专属域名输入框
    toggleDomainInput() {
      this.showDomainInput = !this.showDomainInput;
    },

    // 添加专属域名到列表
    addDomainToList() {
      if (this.form.newDomain) {
        this.form.exclusiveDomains.push(this.form.newDomain);
        this.form.newDomain = ''; // 重置输入框
        this.showDomainInput = false; // 隐藏专属域名输入框
      }
    },

    toggleRemark() {
      this.showRemark = !this.showRemark;
    },

    // 打开添加域名的弹窗
    openDomainDialog() {
      this.domainDialogVisible = true;
      this.isBatchAdd = false;  // 默认显示单个域名输入框
      this.form.newDomain = '';  // 清空之前输入的内容
    },

    // 切换单个和批量添加
    toggleBatchAdd() {
      this.isBatchAdd = !this.isBatchAdd;
    },

    // 添加域名
    addDomain() {
      // 如果是批量添加
      if (this.isBatchAdd) {
        this.addBatchDomains();
      } else {
        this.addSingleDomain();
      }
      this.domainDialogVisible = false;  // 关闭弹窗
    },

    // 添加单个域名
    addSingleDomain() {
      const domain = this.form.newDomain.trim();
      if (domain && !this.form.domains.includes(domain)) {
        this.form.domains.push(domain);
      }
      this.form.newDomain = '';  // 清空输入框
    },

    // 添加批量域名
    addBatchDomains() {
      const domainsToAdd = this.form.newDomain.trim();
      if (!domainsToAdd) return;  // 如果没有输入任何内容，则直接返回

      // 将输入的域名按换行符或逗号分隔
      const domainList = domainsToAdd
        .split(/[\n,]+/)  // 使用正则分隔换行符和逗号
        .map(domain => domain.trim())  // 去除每个域名的空格
        .filter(domain => domain && !this.form.domains.includes(domain));  // 去除空值和重复域名

      if (domainList.length > 0) {
        // 将去重后的域名添加到 form.domains 数组中
        this.form.domains.push(...domainList);
      }

      this.form.newDomain = '';  // 清空输入框
    },

    // 移除域名
    removeDomain(index) {
      this.form.domains.splice(index, 1);
    },

    openOriginDialog() {
      this.originDialogVisible = true;
      this.resetOriginForm()
    },

    addOrigin() {
      this.form.origin = this.form.newOrigin;
      this.originDialogVisible = false;
    },

    openPortDialog() {
      this.portDialogVisible = true;
    },

    addPort() {
      // 根据协议类型生成协议标签（http 或 https）
      const protocolLabel = this.form.protocol === '0' ? 'http' : 'https';
      const portLabel = this.form.newPort || (protocolLabel === 'http' ? '80' : '443');

      // 创建新的端口对象
      let newPort = {
        protocol: this.form.protocol,
        port: portLabel
      };

      // 判断 portParamsList 中是否已存在相同的端口，如果没有则添加
      if (!this.form.portParamsList.some(p => p.protocol === newPort.protocol && p.port === newPort.port)) {
        this.form.portParamsList.push(newPort);
      }

      // 重置端口输入框
      this.form.newPort = '';
      this.portDialogVisible = false;
    },

    removePort(index, port) {
      // 从 portParams 数组中删除指定的端口
      this.form.portParamsList.splice(index, 1);
    },

    // 获取集群列表
    getClusterList() {
      this.loading = true;
      listClusters().then(response => {
        if (response && response.rows && response.rows.length > 0) {
          this.clusters = response.rows;  // 正确赋值给clusters
        } else {
          this.clusters = [];  // 如果没有数据，清空集群列表
        }
        this.loading = false;
      }).catch(error => {
        this.loading = false;
        console.error("Error fetching clusters:", error);
      });
    },

    // 取消
    Cancel() {
      // this.resetOriginForm();
      this.$router.go(-1)
    },

    Submit() {
      // 表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          // 表单验证通过，开始提交数据

          // 提交表单数据
          const formData = {
            ...this.form
          };

          // 你可以在此处执行数据格式化、处理等操作
          console.log('提交的数据: ', formData);

          addServer(formData).then(response => {
            this.$message({
              type: 'success',
              message: '创建网站成功!'
            });
            this.addAuthDialogVisible = false
          }).finally(() => {
            this.$modal.closeLoading()
          });
        } else {
          // 表单验证不通过，提示用户
          console.log('表单验证失败');
          return false;
        }
        this.$router.go(-1);
      });

    }

  }
};
</script>

<style scoped lang="scss">

.help-text {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
  display: block;
}

.more-options {
  margin-left: 120px;
  bottom: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-form-item__helper {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.port-tags {
  display: flex;
  align-items: center;
}

.port-tag {
  margin-right: 8px;
}

.upload-demo {
  margin-top: 20px;
}

.cancel {
  margin-top: 20px;
  margin-left: 50px;
}

.submit {
  margin-top: 20px;
  margin-left: 40px;
}

</style>

